package luke4fun.wheresmymoney.service.async;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.widget.ArrayAdapter;

import java.util.ArrayList;
import java.util.List;

import luke4fun.wheresmymoney.db.AccDBHelper;
import luke4fun.wheresmymoney.db.DBConstants;

public class AsyncAutoCompTask extends AsyncTask<String, String, List<String>> {

	private SQLiteDatabase db;
	private ArrayAdapter<String> adapter;
	private int type;
	
	public AsyncAutoCompTask(Context context, ArrayAdapter<String> adapter, int type) {
		AccDBHelper dbHelper = new AccDBHelper(context);
		this.db = dbHelper.getReadableDatabase();
		this.adapter = adapter;
		this.type = type;
	}
	
	@Override
	protected List<String> doInBackground(String... params) {
		List<String> data = new ArrayList<String>();
		String table = "";
		String columnId = "";
		Cursor cursor;
		switch (type) {
			case 0:
				table	 = DBConstants.TABLE_ITEM;
				columnId = DBConstants.ITEM_ID;
				break;
			case 1:
				table	 = DBConstants.TABLE_CATEGORY;
				columnId = DBConstants.CATEGORY_ID;
				break;
			case 2:
				table	 = DBConstants.TABLE_STORE;
				columnId = DBConstants.STORE_ID;
				break;
		}
		
		cursor = db.query(table, null, null, null, null, null, columnId + " DESC", null);
		while(cursor.moveToNext()) {
			data.add(cursor.getString(cursor.getColumnIndex(DBConstants.ITEM_NAME)));
		}
		db.close();
		return data;
	}

	@Override
	protected void onPostExecute(List<String> result) {
		adapter.clear();
		adapter.addAll(result);
		adapter.notifyDataSetChanged();
	}
}
